package com.study.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.study.common.DataSources;
import com.study.util.DataSourceTypeManager;

@Aspect // for aop
@Component // for auto scan
@Order(0) // execute before @Transactional
public class DataSourceInterceptor {
	@Pointcut("execution(* com.study.service.*.*(..))") // service包中所有类的query打头的方法都用slave库的数据源
	public void dataSourceSlave() {
		System.out.println("====================hahahha==================");
	};

	@Before("dataSourceSlave()")
	public void before(JoinPoint jp) {
//		//输出参数值
//		for (int i = 0; i < jp.getArgs().length; i++) {
//			System.out.println(jp.getArgs()[i]);
//		}
		String methodName = jp.getSignature().getName();
		System.out.println("methodName="+methodName);
		//可写入规则配置中
		if(methodName.indexOf("select")==0 || methodName.indexOf("query")==0 || methodName.indexOf("find")==0){
			DataSourceTypeManager.set(DataSources.SLAVE);
			System.out.println("=============丛库===========");
		}else{
			DataSourceTypeManager.set(DataSources.MASTER);
			System.out.println("=============主库===========");
		}

	}
}